package com.wantupai.translate.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.pdf.PdfDocument;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.wantupai.translate.Constant;
import com.wantupai.translate.R;
import com.wantupai.translate.base.BaseActivity;
import com.wantupai.translate.bean.ChangeBean;
import com.wantupai.translate.bean.DataBean;
import com.wantupai.translate.utils.CommonUtils;
import com.wantupai.translate.utils.ImgUtils;
import com.wantupai.translate.utils.MyLog;
import com.wantupai.translate.utils.NetUtils;
import com.wantupai.translate.utils.NetworkUtils;
import com.wantupai.translate.utils.ShareFileUtils;
import com.wantupai.translate.utils.SspSharePop;
import com.wantupai.translate.utils.SspShareTypePop;
import com.wantupai.translate.utils.SspShareUtils;
import com.wantupai.translate.utils.ToastUtils;
import com.wantupai.translate.utils.WindowUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import static com.wantupai.translate.Constant.ImagePath;

/**
 * @author luxuchang
 * @date 2019/4/25 0025
 * @description
 */
public class ResultActivity extends BaseActivity {
    private String result;
    private TextView tvResult, btnShare, btnCopy;
    private LinearLayout resultParent;
    private ImageView ivClip;
    private String picPath;
    private int curType;
    private SspShareTypePop shareTypePop;
    private SspShareUtils shareUtils;
    private SspSharePop sharePop;
    private Bitmap mBitmap;
    private String path;
    private MediaPlayer mMediaPlayer;
    private AnimationDrawable animationDrawable;
    private TextView btnTrim;
    private TextView btnTranslate;
    private boolean isTrim;

    @Override
    protected boolean translucentStatusBar() {
        return true;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_result;
    }

    @Override
    public void initViews() {
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        result = getIntent().getStringExtra("data");
//        voiceSay(result);
        resultParent = findViewById(R.id.result_parent);
        tvResult = findViewById(R.id.tv_result);
        btnShare = findViewById(R.id.btn_share);
        btnCopy = findViewById(R.id.btn_copy);
        btnTrim = findViewById(R.id.btn_trim);
        btnTranslate = findViewById(R.id.btn_translate);

        ivClip = findViewById(R.id.iv_clip);

        setTitle("结果");

        MyLog.e("sss", WindowUtils.getStatusBarHeight() + "");
        MyLog.e("sss", WindowUtils.px2dip(this, WindowUtils.getStatusBarHeight()) + "");
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tvResult.getLayoutParams();
        lp.setMargins(0, WindowUtils.px2dip(this, WindowUtils.getStatusBarHeight()), 0, 0);
        tvResult.setLayoutParams(lp);

        shareUtils = new SspShareUtils();
        sharePop = new SspSharePop(0, this, new SspSharePop.OnBtnClickListener() {
            @Override
            public void OnBtnClick(final int type) {
                if (curType == 0) {
                    shareUtils.shareText(ResultActivity.this, tvResult.getText().toString(), type);
                } else if (curType == 1) {
                    shareUtils.shareImg(ResultActivity.this, mBitmap, type);
                }
            }
        });


        shareTypePop = new SspShareTypePop(this, new SspShareTypePop.OnBtnClickListener() {
            @Override
            public void OnBtnClick(int type) {
                curType = type;
                if (type == 2) {
                    createPdfObject();
                    savePdf();
                    return;
                }
                if (sharePop != null) {
                    sharePop.show();
                }
            }
        });
    }

    @Override
    public void initListener() {
        btnShare.setOnClickListener(this);
        btnCopy.setOnClickListener(this);
        btnTranslate.setOnClickListener(this);
        btnTrim.setOnClickListener(this);
    }

    @Override
    public void initData() {
        picPath = getIntent().getStringExtra("picPath");
        Glide.with(this).load(Uri.fromFile(new File(picPath))).into(ivClip);

        tvResult.setText(!TextUtils.isEmpty(result) ? result : "");
        tvResult.setMovementMethod(ScrollingMovementMethod.getInstance());

        mBitmap = ImgUtils.img2Bitmap(picPath);
    }

    @Override
    public void processClick(View v) {
        switch (v.getId()) {
            case R.id.btn_share:
                if (shareTypePop != null)
                    shareTypePop.show();
                break;
            case R.id.btn_copy:
                CommonUtils.copyText(result);
                break;
            case R.id.btn_trim:
                if (!isTrim){
                    tvResult.setText(result.replace("\n",""));
                    isTrim = true;
                }else{
                    tvResult.setText(result);
                    isTrim = false;
                }
                break;
            case R.id.btn_translate:
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Tencent.onActivityResultData(requestCode, resultCode, data, new IUiListener() {
            @Override
            public void onComplete(Object o) {
                ToastUtils.show("分享成功");
            }

            @Override
            public void onError(UiError uiError) {
                ToastUtils.show("分享失败");
            }

            @Override
            public void onCancel() {
                ToastUtils.show("分享取消");
            }
        });
    }

    /**
     * 将转成的 PDF 保存到本地
     */
    private void savePdf() {
        try {
            File file = new File(ImagePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            PdfDocument document = new PdfDocument();
            /***宽 高 页数******/
            PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(WindowUtils.getWindowWidth(this), WindowUtils.getWindowHeight(this), 1).create();
            PdfDocument.Page page = document.startPage(pageInfo);

            TextPaint textPaint = new TextPaint();
            textPaint.setColor(Color.BLACK);
            textPaint.setTextSize(16);
            textPaint.setTextAlign(Paint.Align.LEFT);

            Typeface textTypeface = Typeface.create(Typeface.MONOSPACE, Typeface.NORMAL);
            textPaint.setTypeface(textTypeface);

            String text = result;
            StaticLayout mTextLayout = new StaticLayout(text, textPaint, page.getCanvas().getWidth(),
                    Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);

            mTextLayout.draw(page.getCanvas());
            document.finishPage(page);

            File file1 = new File(file, System.currentTimeMillis() + ".pdf");
            path = file1.getPath();
            ShareFileUtils.shareFile(ResultActivity.this, path);
            try {
                FileOutputStream mFileOutStream = new FileOutputStream(file1);

                document.writeTo(mFileOutStream);
                mFileOutStream.flush();
                mFileOutStream.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
            document.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建 PDF 对象
     */
    private void createPdfObject() {
        Document document = new Document();
        try {
            //将文件输出流与pdf对象，进行关联
            PdfWriter.getInstance(document, new FileOutputStream(ImagePath + "table.pdf"));
            //打开文档
            document.open();
            Image img = Image.getInstance(ImagePath + "2.jpg");
            img.setAlignment(Image.LEFT | Image.TEXTWRAP);
            img.setBorder(Image.BOX);
            img.setBorderColor(BaseColor.WHITE);
//            img.scaleToFit(weght, heigth);//大小
            img.setAlignment(Element.ALIGN_CENTER);
            document.add(img);
            //关闭文档
            document.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void voiceSay(String txt) {
//        setFrameAnim(ssp_trans_item_voice);
        Map<String, String> maps = new HashMap<>();
        maps.put("text", txt);
        int NetType = NetworkUtils.getNetWorkType(this);
        if (NetType == 0) {
            Toast.makeText(this, "没有网络连接", Toast.LENGTH_SHORT).show();
        } else {
            NetUtils.getInstance().post(Constant.SSP_API_TEXT2MP3, maps, false, ChangeBean.class, 6, new NetUtils.NetResponseListener() {
                @Override
                public void onSuccess(DataBean result, int requestCode) {
                    ChangeBean data = (ChangeBean) result.getData();
                    MyLog.e("sss","onSuccess==="+data.toString());
                    if (data != null && !TextUtils.isEmpty(data.getAudio_cloud_path()))
                        playMp3(data.getAudio_cloud_path());
                }

                @Override
                public void onFailed(int requestCode, String info) {
                    ToastUtils.show(info);
                    if (animationDrawable != null) {
                        animationDrawable.selectDrawable(0);
                        animationDrawable.stop();
                    }
                }
            });

        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        releasePlayer();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releasePlayer();
    }


    private void playMp3(String mp3) {
        try {
            if (mMediaPlayer != null) {
                mMediaPlayer.stop();
                mMediaPlayer.release();
                mMediaPlayer = null;
            }
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setLooping(false);
            mMediaPlayer.setDataSource(mp3);
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mMediaPlayer.start();
                }
            });
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (animationDrawable != null) {
                        animationDrawable.selectDrawable(0);
                        animationDrawable.stop();
                    }
                }
            });
            mMediaPlayer.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void releasePlayer() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
        if (animationDrawable != null) {
            animationDrawable.selectDrawable(0);
            animationDrawable.stop();
        }
    }

    public void pausePlay() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying())
            mMediaPlayer.pause();
        if (animationDrawable != null) {
            animationDrawable.selectDrawable(0);
            animationDrawable.stop();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        pausePlay();
        releasePlayer();
    }

    private void setFrameAnim(ImageView imageView) {
        imageView.setImageResource(0);
        imageView.setBackground(null);
        if (animationDrawable != null) {
            animationDrawable.selectDrawable(0);
            animationDrawable.stop();
        }
        animationDrawable = new AnimationDrawable();
        // 为AnimationDrawable添加动画帧
        animationDrawable.addFrame(getResources().getDrawable(R.mipmap.ssp_voicegray3), 200);
        animationDrawable.addFrame(getResources().getDrawable(R.mipmap.ssp_voicegray1), 200);
        animationDrawable.addFrame(getResources().getDrawable(R.mipmap.ssp_voicegray2), 200);
        animationDrawable.addFrame(getResources().getDrawable(R.mipmap.ssp_voicegray3), 200);
        // 设置为循环播放
        animationDrawable.setOneShot(false);
        imageView.setImageDrawable(animationDrawable);
        animationDrawable.start();
    }
}
